package org.zj.chat;

import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.stream.ChunkedWriteHandler;

/**
 * 通道初始化器
 * 加载通道处理器
 */
public class WebSocketChannelInitializer extends ChannelInitializer<SocketChannel> {

    //初始化通道
    //加载对应的channelHandler
    protected void initChannel(SocketChannel ch) throws Exception {
        //获取管道,将channelHandler加到管道中
        ChannelPipeline pipeline = ch.pipeline();
        //添加一个http的编解码器
        pipeline.addLast(new HttpServerCodec());
        //添加大数据流支持
        pipeline.addLast(new ChunkedWriteHandler());
        //添加聚合器，将httpMessage聚合成FullHttpRequest/response
        pipeline.addLast(new HttpObjectAggregator(1024*64));//指定缓存数量

        //需要指定接收请求的路由 必须使用以ws后缀结尾的url才能访问
        pipeline.addLast(new WebSocketServerProtocolHandler("/onlineServer"));

        //添加自定义的handler
        pipeline.addLast(new ChatHandler());


    }
}
